package com.maize.uwwireless;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class WaterlooWirelessManager 
{
	public static final int SUCCESS = 0;
	public static final int IOEXCEPTION = -1;
	public static final int CPEXCEPTION = -2;
	public static final int EXCEPTION = -3;
	public static final int ACCEXCEPTION = 1;
	
	private static WaterlooWirelessManager s_Instance;
	private Context context;
	private SharedPreferences prefs;
	
	public static WaterlooWirelessManager getInstance(Context context)
	{
		if (s_Instance == null) 
		{
            s_Instance = new WaterlooWirelessManager(context);
        }
		return s_Instance;	
	}
	
	private WaterlooWirelessManager(Context context)
	{
		this.context = context;
		prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
	}
	
	public int login()
	{
		// Obtain username and password from preferences
    	String username = prefs.getString(Settings.USERNAME, "");
    	String password = prefs.getString(Settings.PASSWORD, "");
    	
    	if (username.equals("") || password.equals("")) return ACCEXCEPTION;
    	
    	DefaultHttpClient httpclient = new DefaultHttpClient(); 
        
        // Get cookies from the login page (not the address same of the form post)
        HttpGet httpget = new HttpGet("https://cn-wc.uwaterloo.ca/upload/custom/uw-portal/index.html");
        
        HttpResponse response;
        try 
        {
             response = httpclient.execute(httpget);
             HttpEntity entity = response.getEntity();
            
             Log.d("httpPost", "Login form get: " + response.getStatusLine());
             if (entity != null) 
             {
                 entity.consumeContent();
             }
             
             Log.d("httpPost", "Initial set of cookies:");
             List<Cookie> cookies = httpclient.getCookieStore().getCookies();
             if (cookies.isEmpty()) 
             {
                  Log.d("httpPost", "None");
             }
             else 
             {
                 for (int i = 0; i < cookies.size(); i++) 
                 {
               	  Log.d("httpPost", "- " + cookies.get(i).toString());
                 }
             }

             // Preparing the post operation (address obtained from the Login page source; it's the form-action)
             HttpPost httpost = new HttpPost("https://cn-wc.uwaterloo.ca/auth/index.html/u");
             
             List <NameValuePair> nvps = new ArrayList <NameValuePair>();
             nvps.add(new BasicNameValuePair("user", username));
             nvps.add(new BasicNameValuePair("password", password));
             
             httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
             
             // Post, check and show the result (not really spectacular, but works):
             response = httpclient.execute(httpost);
             entity = response.getEntity();
             
             Log.d("httpPost", "Login form get: " + response.getStatusLine());
             
             if (entity != null) 
             {
                 entity.consumeContent();
             }
             
             // Send the cookies grabbed from the login form
             Log.d("httpPost", "Post logon cookies:");
             cookies = httpclient.getCookieStore().getCookies();
             if (cookies.isEmpty()) 
             {
                  Log.d("httpPost", "None");
             }
             else 
             {
                 for (int i = 0; i < cookies.size(); i++) 
                 {
               	  Log.d("httpPost", "- " + cookies.get(i).toString());
                 }
             }
             return SUCCESS;
        }
        catch (ClientProtocolException e) 
        {
             Log.e("httpPost", "ClientProtocolException");
             return CPEXCEPTION;
        }
        catch (IOException e) 
        {
             Log.e("httpPost", e.getMessage());
             return IOEXCEPTION;
        }
        catch (Exception e) 
        {
             Log.e("httpPost", e.getMessage());
             return EXCEPTION;
        }
	}
	
	public int logout()
	{
    	String username = prefs.getString(Settings.USERNAME, "");
    	String password = prefs.getString(Settings.PASSWORD, "");
    	
    	if (username.equals("") || password.equals("")) return ACCEXCEPTION;
    	
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost("https://cn-wc.uwaterloo.ca/auth/logout.html");
        HttpResponse response;
        try 
        {
			response = httpclient.execute(httpost);
            Log.d("UW", response.toString());
            Log.d("UW2", "" + response.getStatusLine());
            return SUCCESS;
		}
        catch (ClientProtocolException e) 
        {
        	return CPEXCEPTION;
		}
        catch (IOException e) 
        {
			return IOEXCEPTION;
		}
        catch (Exception e) 
        {
        	return EXCEPTION;
        }
	}
}
